package logic

import (
	"context"
	"errors"
	"shop-login-sys/model/cache"
	"shop-login-sys/model/mysql"
	"shop-login-sys/pkg"

	"shop-login-sys/shoprpc/internal/svc"
	"shop-login-sys/shoprpc/shoprpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginLogic) Login(in *shoprpc.LoginRequest) (*shoprpc.LoginResponse, error) {
	// todo: add your logic here and delete this line
	result, _ := cache.Rdb.Get(l.ctx, "capt"+in.Mobile).Result()
	if result != in.Captcha {
		return nil, errors.New("图形验证码错误,请重新输入")
	}
	resultSms, _ := cache.Rdb.Get(l.ctx, "mobile"+in.Mobile).Result()
	if resultSms != in.Sms {
		return nil, errors.New("短信验证码错误,请重新输入")
	}
	user := &mysql.User{
		//Model:    gorm.Model{},
		Mobile:   in.Mobile,
		Password: pkg.Md5(in.Password),
	}
	err := user.FindUserByMobile(mysql.DB, in.Mobile)
	if err != nil {
		return nil, errors.New("登录失败")
	}
	if user.Password != pkg.Md5(in.Password) {
		return nil, errors.New("密码错误，请重新输入")
	}
	return &shoprpc.LoginResponse{
		UserId: int64(user.ID),
	}, nil
}
